﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace SCCM
{
    public partial class MainWindow : Form
    {
        private SerialPort comm = new SerialPort();
        private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建，定义到外面。
        DataItem newDataItem = new DataItem();//每次接收一次数据，封装在该Item中

        private void a_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'sCCMDataSet.KGGBH' table. You can move, or remove it, as needed.
            this.kGGBHTableAdapter.Fill(this.sCCMDataSet.KGGBH);
            // TODO: This line of code loads data into the 'sCCMDataSet2.KGGBH' table. You can move, or remove it, as needed.

            //初始化下拉串口名称列表框
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            comboPortName.Items.AddRange(ports);
            comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;

            //添加事件注册
            comm.DataReceived += CommDataReceived;
        }
        
        void CommDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = comm.BytesToRead;//先记录下来，避免某种原因，人为的原因，操作几次之间时间长，缓存不一致
            byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
            comm.Read(buf, 0, n);//读取缓冲数据
            builder.Remove(0, builder.Length);//清除字符串构造器的内容

            //string testString = "2015-11-15 15:40;0.0015;0.0025;0.007;-0.003;18.8;70.4;111.4;";
            //buf = System.Text.Encoding.ASCII.GetBytes(testString);
            //直接按ASCII规则转换成字符串
            builder.Append(Encoding.ASCII.GetString(buf));

            //NO2: 0.002; CO: 0.003; NO: 0.008; O3: -0.001; Tem: 19.8C; RH: 68.4 %; Ato: 101.4kPa;
            //0.008;-0.001;19.8;68.4;101.4;2015-11-15 15:40;0.0015;0.0025;0.007;-0.003;18.8;70.4;111.4;2015-11-15 15:39;0.002;0.003;
            //builder.Append("0.008;-0.001;19.8;68.4;101.4;2015-11-15 15:40;0.0015;0.0025;0.007;-0.003;18.8;70.4;111.4;2015-11-15 15:39;0.002;0.003;");

            String[] tks = builder.ToString().Split(';');

            newDataItem.Datetime = tks[0];
            newDataItem.NO2 = Double.Parse(tks[1].Trim());
            newDataItem.CO = Double.Parse(tks[2].Trim());
            newDataItem.NO = Double.Parse(tks[3].Trim());
            newDataItem.O3 = Double.Parse(tks[4].Trim());
            newDataItem.Tem = Double.Parse(tks[5].Trim());
            newDataItem.RH = Double.Parse(tks[6].Trim());
            newDataItem.Ato = Double.Parse(tks[7].Trim());

            MessageBox.Show(newDataItem.ToString());
        }




        public static bool IsDateTime(string StrSource)
        {
            return Regex.IsMatch(StrSource, @"(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d)$");
        }

        public MainWindow()
        {
            InitializeComponent();
        }
        public List<double> getYNO2()
        {
            return yNO2;
        }
        public List<double> getYNO()
        {
            return yNO;
        }
        public List<double> getYCO()
        {
            return yCO;
        }
        public List<double> getO3()
        {
            return yO3;
        }
        public List<double> getYTem()
        {
            return yTem;
        }
        public List<double> getYRH()
        {
            return yRH;
        }
        public List<double> getYAto()
        {
            return yAto;
        }

        List<String> x = new List<string>();

        List<double> yNO2 = new List<double> ();
        
        List<double> yNO = new List<double> ();
        //List<String> xNO = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        List<double> yCO = new List<double> ();
        //List<String> xCO = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        List<double> yO3 = new List<double> ();
        //List<String> xO3 = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        List<double> yTem = new List<double> ();
        // List<String> xTem = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        List<double> yRH = new List<double> ();
        // List<String> xRH = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        List<double> yAto = new List<double> ();
        //  List<String> xAto = new List<string> { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        public void updateData(Chart chart)
        {

            switch (chart.Name)
            {
                case "NO2Chart":
                    chart.Series[0].Points.DataBindXY(x, yNO2);
                    break;
                case "NOChart":
                    chart.Series[0].Points.DataBindXY(x, yNO);
                    break;
                case "COChart":
                    chart.Series[0].Points.DataBindXY(x, yCO);
                    break;
                case "O3Chart":
                    chart.Series[0].Points.DataBindXY(x, yO3);
                    break;
                case "TemChart":
                    chart.Series[0].Points.DataBindXY(x, yTem);
                    break;
                case "RHChart":
                    chart.Series[0].Points.DataBindXY(x, yRH);
                    break;
                case "AtoChart":
                    chart.Series[0].Points.DataBindXY(x, yAto);
                    break;
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
                DataBase dataBase = new DataBase();

                string dt = DateTime.Now.ToString("yyyy-mm-dd hh:mm");

                double newY = new Random().Next(5, 10);
                yNO2.Add(newY);
                x.Add(dt);
                
                dataBase.Insert(newY, dt, "NO2", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());
                //yNO2.RemoveAt(0);
                //x.RemoveAt(0);
                updateData(NO2Chart);
                //----------------------------------
                newY =  new Random().Next(5, 10);

                yNO.Add(newY);
                dataBase.Insert(newY, dt, "NO", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());

                //yNO.RemoveAt(0);
                updateData(NOChart);
                //----------------------------------
                newY =  new Random().Next(5, 10);
                yCO.Add(newY);
                dataBase.Insert(newY, dt, "CO", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());

                //yCO.RemoveAt(0);
                updateData(COChart);
                //----------------------------------
                newY =  new Random().Next(5, 10);
                yO3.Add(newY);
                dataBase.Insert(newY, dt, "O3", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());

                //yO3.RemoveAt(0);
                updateData(O3Chart);
                //----------------------------------       
                newY =  new Random().Next(5, 10);
                yTem.Add(newY);
                dataBase.Insert(newY, dt, "Tem", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());

                //yTem.RemoveAt(0);
                updateData(TemChart);
                //----------------------------------
                newY =  new Random().Next(5, 10);
                yRH.Add(newY);
                dataBase.Insert(newY, dt, "RH", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());

                //yRH.RemoveAt(0);
                updateData(RHChart);
                //----------------------------------
                newY =  new Random().Next(5, 10);
                yAto.Add(newY);
                dataBase.Insert(newY, dt, "Ato", bianDianZhan.Text.Trim().ToString(), kaiGuanShi.Text.Trim().ToString(), kaiGuanGui.Text.Trim().ToString());

                //yAto.RemoveAt(0);
                updateData(AtoChart);
      

        }

        private void liShiShuju_Click(object sender, EventArgs e)
        {
            HistoryWindow history = new HistoryWindow();
            history.Show();
        }

        private void jieShu_Click(object sender, EventArgs e)
        {
            if (comm.IsOpen)
            {
                //打开时点击，则关闭串口
                comm.Close();
            }
            
        }

        private void caiJi_Click(object sender, EventArgs e)
        {
            //根据当前串口对象，来判断操作
            if (!comm.IsOpen)
            {
                //关闭时点击，则设置好端口，波特率后打开
                comm.PortName = comboPortName.Text;
                comm.BaudRate = 115200;
                comm.DataBits = 8;
                comm.Parity = Parity.None;
                comm.StopBits = StopBits.One;

                try
                {
                    comm.Open();
                }
                catch (Exception ex)
                {
                    //捕获到异常信息，创建一个新的comm对象，之前的不能用了。
                    comm = new SerialPort();
                    //现实异常信息给客户。
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void NO2Chart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yNO2);
            publicPlot.SetTile("NO2");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }
        private void NOChart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yNO);
            publicPlot.SetTile("NO");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }

        private void COChart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yCO);
            publicPlot.SetTile("CO");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }

        private void O3Chart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yO3);
            publicPlot.SetTile("O3");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }

        private void TemChart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yTem);
            publicPlot.SetTile("Tem");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }

        private void RHChart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yRH);
            publicPlot.SetTile("RH");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }

        private void AtoChart_Click(object sender, EventArgs e)
        {
            PublicPlot publicPlot = new PublicPlot();
            publicPlot.SetX(x);
            publicPlot.SetY(yAto);
            publicPlot.SetTile("Ato");
            publicPlot.SetForm(this);
            publicPlot.Show();
        }
    }
}
